<template>
  <div class="header-container">
    <div class="header-left">
      <el-button
        :icon="collapsed ? 'Expand' : 'Fold'"
        @click="toggleCollapse"
        circle
        size="small"
      />
    </div>
    <div class="header-right">
      <slot name="right" />
      <!-- 清除缓存按钮 -->
      <el-tooltip content="清除缓存数据" placement="bottom" effect="light">
        <el-button
          type="primary"
          circle
          size="small"
          icon="Refresh"
          @click="clearCache"
          class="clear-cache-btn"
        />
      </el-tooltip>
      <!-- 用户信息和下拉菜单 -->
      <el-dropdown @command="handleCommand">
        <span class="user-info">
          <el-avatar v-if="userinfo.avatar" size="small" :src="userinfo.avatar" />
          <el-icon v-else><Setting /></el-icon>
          <span style="margin-left: 8px">{{ userinfo.username || '用户' }}</span>
          <el-icon class="arrow-down">
            <ArrowDown />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">基本信息</el-dropdown-item>
            <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>

  <!-- 修改密码抽屉 -->
  <GlobalDrawer
    v-model="changePasswordDrawerVisible"
    title="修改密码"
    size="500px"
    @confirm="handleChangePassword"
    @close="handleCloseChangePasswordDrawer"
  >
    <el-form
      ref="changePasswordFormRef"
      :model="changePasswordForm"
      :rules="changePasswordRules"
      label-width="100px"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="changePasswordForm.oldPassword"
          type="password"
          show-password
          placeholder="请输入旧密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="changePasswordForm.newPassword"
          type="password"
          show-password
          placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="changePasswordForm.confirmPassword"
          type="password"
          show-password
          placeholder="请再次输入新密码"
        />
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import {
    ElButton,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElAvatar,
    ElIcon,
    ElMessage,
    ElMessageBox,
    ElTooltip,
    ElForm,
    ElFormItem,
    ElInput,
  } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ArrowDown, User, Setting, Refresh } from '@element-plus/icons-vue'
  import { useUserStore } from '@/store/user'
  import { useRouter } from 'vue-router'
  import config from '../../config'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  const router = useRouter()
  const userStore: any = useUserStore()

  const props = defineProps<{
    collapsed: boolean
  }>()

  const emit = defineEmits<{
    (e: 'update:collapsed', value: boolean): void
    (e: 'openProfileDrawer'): void // 添加打开个人信息抽屉事件
  }>()

  const toggleCollapse = () => {
    emit('update:collapsed', !props.collapsed)
  }

  // 从Pinia状态管理中获取用户信息
  const userinfo = computed(() => {
    // 优先从store获取，如果store中没有则从localStorage获取
    if (userStore.userInfo && userStore.userInfo.id) {
      return {
        username: userStore.userInfo.nickname || userStore.userInfo.username || '用户',
        avatar: userStore.userInfo.avatar || '',
      }
    }

    // 如果store中没有，尝试从localStorage恢复
    try {
      const cachedUserInfo = localStorage.getItem('userInfo')
      if (cachedUserInfo) {
        const parsedInfo = JSON.parse(cachedUserInfo)
        return {
          username: parsedInfo.nickname || parsedInfo.username || '用户',
          avatar: parsedInfo.avatar || '',
        }
      }
    } catch (e) {}

    return {
      username: '用户',
      avatar: '',
    }
  })

  // 处理下拉菜单命令
  const handleCommand = (command: string) => {
    if (command === 'logout') {
      // 调用退出登录
      logout()
    } else if (command === 'profile') {
      // 触发打开个人信息抽屉事件，而不是跳转页面
      emit('openProfileDrawer')
    } else if (command === 'changePassword') {
      // 打开修改密码抽屉
      openChangePasswordDrawer()
    }
  }

  // 退出登录函数
  const logout = async () => {
    await ElMessageBox.confirm('确定退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          // 调用退出登录方法
          await userStore.logoutAction()
          ElMessage.success('已退出登录')

          // 强制清除页面状态和缓存
          localStorage.clear()
          sessionStorage.clear()

          // 更可靠的页面跳转机制
          // 1. 先尝试Vue Router跳转
          router.replace('/login').catch(() => {
            // 2. 如果路由跳转失败，强制刷新整个页面
            window.location.href = '/login'
          })

          // 设置一个较短的超时，确保无论如何都会刷新页面
          setTimeout(() => {
            // 检查当前路径，如果不是登录页则强制跳转
            if (window.location.pathname !== '/login') {
              window.location.href = '/login'
            }
          }, 100)
        } catch (error) {
          ElMessage.error('退出登录失败')
        }
      })
      .catch(() => {
        // 取消退出登录
      })
  }

  // 清除缓存函数
  const clearCache = () => {
    try {
      // 定义需要清除的缓存键名
      const CACHE_KEYS = [
        'customer_admin_list_cache',
        'customer_grade_options_cache',
        'customer_status_options_cache',
        'customer_source_options_cache',
        'permission_list',
        'role_list',
        'menu_list',
        'user_selector_departments_cache', // 添加用户选择器部门缓存
        'user_selector_users_cache', // 添加用户选择器用户缓存
      ]

      // 先保存token和userInfo的值，确保用户不需要重新登录
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')

      // 清除指定的缓存数据
      CACHE_KEYS.forEach(key => {
        localStorage.removeItem(key)
        // 已清除缓存
      })

      // 显示成功提示
      ElMessage.success('缓存已成功清除，请刷新页面查看最新数据')
    } catch (error) {
      console.error('清除缓存失败:', error)
      ElMessage.error('清除缓存时发生错误')
    }
  }

  // 修改密码抽屉相关
  const changePasswordDrawerVisible = ref(false)
  const changePasswordFormRef = ref<FormInstance>()
  const changePasswordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  })

  // 修改密码表单验证规则
  const changePasswordRules = ref<FormRules>({
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (value !== changePasswordForm.value.newPassword) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
  })

  // 打开修改密码抽屉
  const openChangePasswordDrawer = () => {
    changePasswordDrawerVisible.value = true
  }

  // 关闭修改密码抽屉
  const handleCloseChangePasswordDrawer = () => {
    changePasswordFormRef.value?.resetFields()
    changePasswordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    }
  }

  // 处理修改密码
  const handleChangePassword = async () => {
    if (!changePasswordFormRef.value) return

    await changePasswordFormRef.value.validate(async valid => {
      if (valid) {
        try {
          const res = await userStore.changePasswordAction({
            old_password: changePasswordForm.value.oldPassword,
            new_password: changePasswordForm.value.newPassword,
          })

          if (res.code === 0) {
            ElMessage.success('密码修改成功')
            handleCloseChangePasswordDrawer()
            changePasswordDrawerVisible.value = false
          } else {
            ElMessage.error(res.msg || '密码修改失败')
          }
        } catch (error: any) {
          ElMessage.error(error.message || '密码修改失败')
        }
      }
    })
  }
</script>

<style scoped>
  .header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 60px;
    padding: 0 10px;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
    border-bottom: 1px solid #e8e8e8;
    margin-left: 0; /* 移除左侧外边距 */
  }

  .header-left {
    display: flex;
    align-items: center;
  }

  .header-right {
    display: flex;
    align-items: center;
  }

  .clear-cache-btn {
    margin-right: 15px;
    transition: all 0.3s;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .clear-cache-btn:hover {
    transform: rotate(180deg);
    transition: all 0.5s;
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
  }

  .user-info {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;
    color: #303133;
  }

  .arrow-down {
    margin-left: 4px;
  }

  .user-icon {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
